package com.generic.mybatis.dal.dao.criteria;

import com.generic.mybatis.dal.interceptor.automap.TableMapper;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;

/**
 * In
 *
 * @author wuaj
 */
public class InCriteria extends FieldCriteria {

    public InCriteria(String field, Object... values) {
        super(field, values);
    }

    @Override
    public void toSql(TableMapper mapper, SQL sql, Map paramMap) {
        if (Array.getLength(value) > 0) {
            String paramName;
            List<String> names = Lists.newArrayList();
            for (int index = 0; index < Array.getLength(value); index++) {
                paramName = getParameterName(mapper);
                paramMap.put(paramName, Array.get(value, index));
                names.add(String.format("#{%s}", paramName));
            }
            sql.WHERE(String.format("%s in (  %s )", getAlias(mapper), StringUtils.join(names, ",")));
        }
    }
}